﻿/*
 * Author: .net follower (http://dotnetfollower.com)
 * Copyright: � 2012 .net follower 
 * Usage: software is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND.
 */

using System;
using System.Collections.Generic;
using System.Xml.Linq;
using System.Xml.XPath;
using WebLoading;

namespace TestApp
{
    public class GraphicalWeatherLoader : XmlLoader<List<GraphicalWeatherLoader.DailyMaximumTemperature>>
    {
        public class DailyMaximumTemperature
        {
            public DateTime Day         { get; set; }
            public string   Temperature { get; set; }
        }

        protected static string _urlTemplate = "http://graphical.weather.gov/xml/SOAP_server/ndfdXMLclient.php?whichClient=NDFDgenMultiZipCode&lat=&lon=&listLatLon=&lat1=&lon1=&lat2=&lon2=&resolutionSub=&listLat1=&listLon1=&listLat2=&listLon2=&resolutionList=&endPoint1Lat=&endPoint1Lon=&endPoint2Lat=&endPoint2Lon=&listEndPoint1Lat=&listEndPoint1Lon=&listEndPoint2Lat=&listEndPoint2Lon=&zipCodeList={0}&listZipCodeList=&centerPointLat=&centerPointLon=&distanceLat=&distanceLon=&resolutionSquare=&listCenterPointLat=&listCenterPointLon=&listDistanceLat=&listDistanceLon=&listResolutionSquare=&citiesLevel=&listCitiesLevel=&sector=&gmlListLatLon=&featureType=&requestedTime=&startTime=&endTime=&compType=&propertyName=&product=time-series&begin=2004-01-01T00%3A00%3A00&end=2016-06-27T00%3A00%3A00&Unit=e&maxt=maxt&Submit=Submit";

        public GraphicalWeatherLoader(string zipCode) : base(string.Format(_urlTemplate, zipCode))
        {
        }

        protected override List<GraphicalWeatherLoader.DailyMaximumTemperature> ParseData(XDocument rawData)
        {
            List<DailyMaximumTemperature> res = new List<DailyMaximumTemperature>();

            XElement dataElement = rawData.XPathSelectElement("dwml/data");

            IEnumerator<XElement> dates        = dataElement.XPathSelectElements("time-layout/start-valid-time").GetEnumerator();
            IEnumerator<XElement> temperatures = dataElement.XPathSelectElements("parameters/temperature/value").GetEnumerator();
            
            while(dates.MoveNext() && temperatures.MoveNext())
            {
                DailyMaximumTemperature dailyMaximumTemperature = new DailyMaximumTemperature();
                dailyMaximumTemperature.Day         = DateTime.Parse(dates.Current.Value);
                dailyMaximumTemperature.Temperature = temperatures.Current.Value;
                res.Add(dailyMaximumTemperature);
            }            

            return res;
        }

        protected override bool IsRawDataValid(XDocument rawData)
        {
            string data = rawData.ToString();
            if(!string.IsNullOrWhiteSpace(data))
                return !data.Contains("SOAP ERROR");
            return false;
        }
    }
}
